package com.softstao.guoyu.ui.activity.sale;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.softstao.guoyu.R;
import com.softstao.guoyu.base.BaseActivity;
import com.softstao.guoyu.global.SharePreferenceManager;
import com.softstao.guoyu.global.UserManager;
import com.softstao.guoyu.model.sale.PayCondition;
import com.softstao.guoyu.model.sale.ToOrder;
import com.softstao.guoyu.model.sale.ToOrderList;
import com.softstao.guoyu.mvp.interactor.sale.OrderInteractor;
import com.softstao.guoyu.mvp.presenter.sale.OrderPresenter;
import com.softstao.guoyu.mvp.viewer.sale.OrderViewer;
import com.softstao.guoyu.mvp.viewer.sale.ToAgentOrderListViewer;
import com.softstao.guoyu.ui.adapter.ToOrderAdapter;
import com.softstao.guoyu.widget.HintDialog;
import com.softstao.softstaolibrary.library.utils.LZUtils;
import com.softstao.softstaolibrary.library.widget.CustomScrollerView;
import com.softstao.softstaolibrary.library.widget.EmptyLayout;
import com.softstao.softstaolibrary.library.widget.FullyLinearLayoutManager;
import com.softstao.softstaolibrary.library.widget.LZToast;
import com.softstao.softstaolibrary.library.widget.MarginDecoration2;
import com.wangjie.androidinject.annotation.annotations.mvp.AIPresenter;

import net.lucode.hackware.magicindicator.FragmentContainerHelper;
import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by vaikus on 2017/6/16.
 */

public class ToAgentOrderListActivity extends BaseActivity implements ToAgentOrderListViewer, ToOrderAdapter.AdapterItemListener, OrderViewer, TextWatcher {

    @AIPresenter(presenter = OrderPresenter.class, interactor = OrderInteractor.class)
    OrderPresenter presenter;

    @BindView(R.id.tab_strip)
    MagicIndicator tabStrip;
    @BindView(R.id.tab_layout)
    SegmentTabLayout tabLayout;
    @BindView(R.id.search_v)
    EditText searchView;
    @BindView(R.id.list_view)
    RecyclerView listView;
    @BindView(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @BindView(R.id.more)
    TextView more;
    @BindView(R.id.scroll_view)
    CustomScrollerView scrollView;
    @BindView(R.id.loading)
    RelativeLayout loading;
    @BindView(R.id.top)
    ImageView top;
    private String[] mTitles = {"待支付", "已支付", "被驳回"};
    private CommonNavigator commonNavigator;
    private FragmentContainerHelper mFragmentContainerHelper;
    private String[] tabs = new String[]{"全部", "待确认", "待付款", "待发货", "待收货", "已收货", "已取消"};
    private String orderState = "";
    private String keyword = "";
    private List<ToOrder> orderLists = new ArrayList<>();
    private ToOrderAdapter orderAdapter;
    private int position;
    private PayCondition payCondition = new PayCondition();
    private final static int PAY = 3;
    private int isPay = 0;

    @Override
    public int _ContentView() {
        return R.layout.activity_order_list;
    }

    @Override
    public void initView() {
        initTitle("我发起的采购单");
        emptyLayout.setEmptyLayout(R.layout.layout_no_order);
        scrollView.setOnScrollChangedListener(this);
        scrollView.setImgeViewOnClickGoToFirst(top);
        setPtrFrameLayoutEnable();
        search();

        tabLayout.setTabData(mTitles);
        orderState = getIntent().getStringExtra("orderState");
        if (orderState.equals("1")) {
            tabLayout.setVisibility(View.VISIBLE);
        } else {
            tabLayout.setVisibility(View.GONE);
        }

        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                switch (mTitles[position]) {
                    case "待支付":
                        currentPage = 1;
                        isPay = 0;
                        toAgentOrder();
                        break;
                    case "已支付":
                        currentPage = 1;
                        isPay = 1;
                        toAgentOrder();
                        break;
                    case "被驳回":
                        currentPage = 1;
                        isPay = 2;
                        toAgentOrder();
                        break;
                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return tabs.length;
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                ColorTransitionPagerTitleView colorTransitionPagerTitleView = new ColorTransitionPagerTitleView(context);
                colorTransitionPagerTitleView.setNormalColor(getResources().getColor(R.color.font_gray));
                colorTransitionPagerTitleView.setSelectedColor(getResources().getColor(R.color.font_pink));
                colorTransitionPagerTitleView.setText(tabs[index]);
                colorTransitionPagerTitleView.setTextSize(14);
                colorTransitionPagerTitleView.setWidth(getScreenWidth() / 4);
                colorTransitionPagerTitleView.setOnClickListener(v -> {
                    //点击事件
                    mFragmentContainerHelper.handlePageSelected(index);
                    tabLayout.setVisibility(View.GONE);
                    switch (index) {
                        case 0:
                            orderState = "";
                            break;
                        case 1:
                            orderState = String.valueOf(ToOrder.UNCONFIRM);
                            break;
                        case 2:
                            orderState = String.valueOf(ToOrder.UNPAY);
                            isPay = 0;
                            if (UserManager.getInstance().getUser().getLevel()!=5) {
                                tabLayout.setVisibility(View.VISIBLE);
                                tabLayout.setCurrentTab(0);
                            }
                            break;
                        case 3:
                            orderState = String.valueOf(ToOrder.PAYED);
                            break;
                        case 4:
                            orderState = String.valueOf(ToOrder.SHIPPED);
                            break;
                        case 5:
                            orderState = String.valueOf(ToOrder.COMPLETED);
                            break;
                        case 6:
                            orderState = String.valueOf(ToOrder.CANCEL);
                            break;
                    }
                    currentPage = 1;
                    toAgentOrder();
                });
                return colorTransitionPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_WRAP_CONTENT);
                indicator.setColors(getResources().getColor(R.color.font_pink));
                return indicator;
            }
        });
        tabStrip.setNavigator(commonNavigator);
        commonNavigator.getChildAt(0).setHorizontalFadingEdgeEnabled(true);
        commonNavigator.getChildAt(0).setFadingEdgeLength(10);
        mFragmentContainerHelper = new FragmentContainerHelper(tabStrip);
        switch (orderState) {
            case "":
                mFragmentContainerHelper.handlePageSelected(0);
                break;
            case ToOrder.UNCONFIRM+"":
                mFragmentContainerHelper.handlePageSelected(1);
                break;
            case ToOrder.UNPAY+"":
                mFragmentContainerHelper.handlePageSelected(2);
                break;
            case ToOrder.PAYED+"":
                mFragmentContainerHelper.handlePageSelected(3);
                break;
            case ToOrder.SHIPPED+"":
                mFragmentContainerHelper.handlePageSelected(4);
                break;
            case ToOrder.COMPLETED+"":
                mFragmentContainerHelper.handlePageSelected(5);
                break;
            case ToOrder.CANCEL+"":
                mFragmentContainerHelper.handlePageSelected(6);
                break;
        }

        orderAdapter = new ToOrderAdapter(orderLists);
        orderAdapter.setAdapterItemListener(this);
        orderAdapter.setListener(position -> {
            Intent intent = new Intent(getContext(), OrderDetailActivity.class);
            intent.putExtra("order_code", orderLists.get(position).getOrderCode());
            intent.putExtra("order_title", "to_order");
            startActivity(intent);
        });
        listView.setAdapter(orderAdapter);
        listView.setLayoutManager(new FullyLinearLayoutManager(this));
        listView.addItemDecoration(new MarginDecoration2(this));

        presenter = new OrderPresenter();
        presenter.setInteractor(new OrderInteractor());
        presenter.setViewer(this);
        currentPage = 1;
        toAgentOrder();
    }

    private void search() {
        searchView.setHint("订单编号/收货人-");
        searchView.addTextChangedListener(this);
        searchView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        searchView.setInputType(EditorInfo.TYPE_CLASS_TEXT);
        searchView.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                try {
                    keyword = URLEncoder.encode(searchView.getText().toString(), "utf-8");
                    currentPage = 1;
                    toAgentOrder();
                    InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                    mInputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return false;
            }
            return true;
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        toAgentOrder();
    }

    @Override
    public void onRefresh() {
        super.onRefresh();
        toAgentOrder();
    }

    @Override
    public void onLoad() {
        super.onLoad();
        toAgentOrder();
    }

    @Override
    public void toAgentOrder() {
        loading.setVisibility(View.VISIBLE);
        presenter.getToAgentOrderList("to",currentPage, SharePreferenceManager.getInstance().getAgentId(), orderState, keyword, isPay);
    }

    @Override
    public void getOrderList(ToOrderList orderList) {
        loading.setVisibility(View.GONE);
        if (orderList != null) {
            if (orderList.getOrderList() != null && orderList.getOrderList().size() != 0) {
                emptyLayout.setVisibility(View.GONE);
                more.setVisibility(View.GONE);
                if (currentPage == 1) {
                    orderLists.clear();
                }
                orderLists.addAll(orderList.getOrderList());
                orderAdapter.notifyDataSetChanged();
            } else {
                if (currentPage == 1) {
                    orderLists.clear();
                    orderAdapter.notifyDataSetChanged();
                    emptyLayout.setVisibility(View.VISIBLE);
                } else {
                    more.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    @Override
    protected void error(String msg) {
        super.error(msg);
        loading.setVisibility(View.GONE);
    }

    @Override
    public void onCancel(int position) {
        this.position = position;
        new AlertDialog.Builder(context)
                .setMessage("确定取消订单吗？")
                .setPositiveButton("确定",(dialog1, which) -> {
                    dialog1.dismiss();
                    orderCancel();
                })
                .setNegativeButton("取消",(dialog1, which) -> dialog1.dismiss())
                .create().show();
    }

    @Override
    public void onShouhuo(int position) {
        this.position = position;
        HintDialog dialog = new HintDialog(context, R.style.MyDialog);
        dialog.getWindow().setLayout(getScreenWidth() - LZUtils.dipToPix(context, 30) * 2, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.getIcon().setVisibility(View.GONE);
        dialog.setTitle("确认收货");
        dialog.setContentVisible();
        dialog.setContent("确认收货吗？");
        dialog.setCancelVisible();
        dialog.setConfirm("确认");
        dialog.getConfirm().setOnClickListener(v1 -> {
            orderReceive();
            dialog.dismiss();
        });
        dialog.show();
    }

    @Override
    public void onItemClick(int mPosition, int position) {
        Intent intent = new Intent(getContext(), OrderDetailActivity.class);
        intent.putExtra("order_code", orderLists.get(mPosition).getOrderCode());
        intent.putExtra("order_title", "to_order");
        startActivity(intent);
    }

    @Override
    public void onPay(int position) {
        this.position = position;
        Intent intent = new Intent(context, OrderPayActivity.class);
        intent.putExtra("order_detail", orderLists.get(position));
        intent.putExtra("status", "to");
        startActivityForResult(intent, PAY);
    }

    @Override
    public void onPayAgain(int position) {
        this.position = position;
        Intent intent = new Intent(context, OrderPayActivity.class);
        intent.putExtra("order_detail", orderLists.get(position));
        intent.putExtra("status", "to");
        startActivityForResult(intent, PAY);
    }

    @Override
    public void onSubmitAgain(int position) {
        this.position = position;
        new AlertDialog.Builder(context)
                .setMessage("确定重新提交订单？")
                .setPositiveButton("确定",(dialog1, which) -> {
                    orderResubmit();
                    dialog1.dismiss();
                }).setNegativeButton("取消",(dialog1, which) -> dialog1.dismiss())
                .create().show();
    }

    @Override
    public void onDelete(int position) {
        this.position = position;
        new AlertDialog.Builder(context)
                .setMessage("确定删除此订单？")
                .setPositiveButton("确定",(dialog1, which) -> {
                    orderDelete();
                    dialog1.dismiss();
                }).setNegativeButton("取消",(dialog1, which) -> dialog1.dismiss())
                .create().show();
    }

    @Override
    public void orderCancel() {
        loading.setVisibility(View.VISIBLE);
        presenter.orderCancel(SharePreferenceManager.getInstance().getAgentId(), orderLists.get(position).getOrderCode(), "");
    }

    @Override
    public void orderConfirmIncome() {

    }

    @Override
    public void orderRejectIncome() {

    }

    @Override
    public void orderSubmitShipping() {

    }

    @Override
    public void orderPay() {
        loading.setVisibility(View.VISIBLE);
        presenter.orderPay(payCondition);
    }

    @Override
    public void orderConfirm() {

    }

    @Override
    public void orderResubmit() {
        loading.setVisibility(View.VISIBLE);
        presenter.orderResubmit(SharePreferenceManager.getInstance().getAgentId(),orderLists.get(position).getOrderCode());
    }

    @Override
    public void orderTransfer() {

    }

    @Override
    public void orderReceive() {
        loading.setVisibility(View.VISIBLE);
        presenter.orderReceive(SharePreferenceManager.getInstance().getAgentId(),orderLists.get(position).getOrderCode());
    }

    @Override
    public void orderRevoke() {

    }

    @Override
    public void orderDelete() {
        loading.setVisibility(View.VISIBLE);
        presenter.orderDelete(SharePreferenceManager.getInstance().getAgentId(), orderLists.get(position).getOrderCode());
    }

    @Override
    public void cancelResult(Object result) {
        loading.setVisibility(View.GONE);
        HintDialog dialog = new HintDialog(context, R.style.MyDialog);
        dialog.getWindow().setLayout(getScreenWidth() - LZUtils.dipToPix(context, 55) * 2, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.setIcon(R.mipmap.hint_icon_success);
        dialog.setTitle("取消订单成功");
        dialog.setConfirm("确认");
        dialog.getConfirm().setOnClickListener(v -> dialog.dismiss());
        dialog.show();
        scrollView.smoothScrollTo(0,0);
        currentPage = 1;
        toAgentOrder();
    }

    @Override
    public void confirmIncomeResult(Object result) {

    }

    @Override
    public void rejectIncomeResult(Object result) {

    }

    @Override
    public void submitShippingResult(Object result) {

    }

    @Override
    public void payResult(Object result) {
        loading.setVisibility(View.GONE);
        HintDialog dialog = new HintDialog(context, R.style.MyDialog);
        dialog.getWindow().setLayout(getScreenWidth() - LZUtils.dipToPix(context, 55) * 2, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.setIcon(R.mipmap.hint_icon_success);
        dialog.setTitle("付款成功");
        dialog.setContentVisible();
        dialog.setContent("请耐心等待发货!");
        dialog.setConfirm("确认");
        dialog.getConfirm().setOnClickListener(v -> dialog.dismiss());
        dialog.show();
        scrollView.smoothScrollTo(0,0);
        currentPage = 1;
        toAgentOrder();
    }

    @Override
    public void confirmResult(Object result) {

    }

    @Override
    public void reSubmitResult(Object result) {
        loading.setVisibility(View.GONE);
        LZToast.getInstance(context).showToast("提交成功");
        scrollView.smoothScrollTo(0,0);
        currentPage = 1;
        toAgentOrder();
    }

    @Override
    public void transferResult(Object result) {

    }

    @Override
    public void receiveResult(Object result) {
        loading.setVisibility(View.GONE);
        LZToast.getInstance(context).showToast("确认收货成功");
        scrollView.smoothScrollTo(0,0);
        currentPage = 1;
        toAgentOrder();
    }

    @Override
    public void revokeResult(Object result) {

    }

    @Override
    public void deleteResult(Object result) {
        loading.setVisibility(View.GONE);
        orderAdapter.notifyItemRemoved(position);
        orderLists.remove(position);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PAY:
                    payCondition = (PayCondition) data.getSerializableExtra("pay");
                    payCondition.setAgentId(SharePreferenceManager.getInstance().getAgentId());
                    payCondition.setOrderCode(orderLists.get(position).getOrderCode());
                    orderPay();
                    break;
            }
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (searchView.getText().toString().equals("")){
            keyword = "";
            currentPage = 1;
            toAgentOrder();
        }
    }
}
